package com.zxy.zxyrpc.loadBalancer;

import com.zxy.zxyrpc.model.ServiceMetaInfo;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 加权轮询负载器(默认第一台服务器性能最优)
 *      方案: 1.二分算法
 *           2.分列表
 *
 * @author zxy
 * @since 2025/5/27
 **/
public class WeightRoundRobinLoadBanlancer implements LoadBalancer {
    private final AtomicInteger currentIndex = new AtomicInteger(0);

    @Override
    public ServiceMetaInfo select(Map<String, Object> reqParams, List<ServiceMetaInfo> serviceMetaInfoList) {
        // 为空则为空，只有一个就无需轮询
        if (serviceMetaInfoList.isEmpty())
            return null;
        int size = serviceMetaInfoList.size();
        if (1 == size)
            return serviceMetaInfoList.get(0);
        // 轮询取模算法
        /*serviceMetaInfoList.sort((data1, data2) -> {
            Integer weight1 = data1.getWeight();
            Integer weight2 = data2.getWeight();
            return weight1.compareTo(weight2);
        });*/
        serviceMetaInfoList = serviceMetaInfoList.stream()
                .sorted(Comparator.comparing(ServiceMetaInfo::getWeight))
                .collect(Collectors.toList());
        // 默认取最优
        int index = 0;
        if (currentIndex.get() % 3 == 0)
            // todo 如果是三台服务，就有问题
            index = currentIndex.getAndIncrement() % size;
        else currentIndex.getAndIncrement();
        return serviceMetaInfoList.get(index);
    }
}
